<template>
    <view class="login-container">
        <view class="login-card">
            <view class="login-logo">
                <image src="/static/logo.png" mode="widthFix"></image>
            </view>
            <view class="login-title">
                <text>后台管理系统</text>
            </view>
            <view class="login-form">
                <view class="form-item">
                    <view class="form-label">用户名</view>
                    <input class="form-input" type="text" placeholder="请输入用户名" v-model="loginForm.username" />
                </view>
                <view class="form-item">
                    <view class="form-label">密码</view>
                    <input class="form-input" type="password" placeholder="请输入密码" v-model="loginForm.password" />
                </view>
                <view class="login-button" @click="handleLogin" :class="{ disabled: loading }">
                    <text>{{ loading ? '登录中...' : '登录' }}</text>
                </view>
                <view class="login-tip" v-if="showInitTip">
                    <text>提示：首次使用，请先初始化管理员账号</text>
                    <view class="init-button" @click="initAdminUser">初始化Admin账号</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const loginForm = ref({
    username: '',
    password: ''
});

// 加载状态
const loading = ref(false);
// 是否显示初始化提示
const showInitTip = ref(false);

// 登录处理
const handleLogin = async () => {
    if (loading.value) return;

    if (!loginForm.value.username || !loginForm.value.password) {
        uni.showToast({
            title: '请输入用户名和密码',
            icon: 'none'
        });
        return;
    }

    loading.value = true;

    try {
        // 调用登录云函数
        const loginResult = await uniCloud.callFunction({
            name: 'login',
            data: {
                username: loginForm.value.username,
                password: loginForm.value.password
            }
        });

        const { result } = loginResult;

        if (result.code === 0) {
            // 登录成功
            // 存储用户信息和token
            uni.setStorageSync('token', result.data.token);
            uni.setStorageSync('userInfo', result.data.userInfo);
            uni.setStorageSync('isLoggedIn', true);

            uni.showToast({
                title: '登录成功',
                icon: 'success'
            });

            // 跳转到首页
            setTimeout(() => {
                uni.reLaunch({
                    url: '/pages/index/index'
                });
            }, 1500);
        } else if (result.code === -2) {
            // 用户不存在，可能是首次使用，显示初始化提示
            showInitTip.value = true;
            uni.showToast({
                title: result.message,
                icon: 'none'
            });
        } else {
            // 其他错误
            uni.showToast({
                title: result.message || '登录失败',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('登录失败', error);
        // 如果是连接云函数失败，可能是首次使用
        showInitTip.value = true;
        uni.showToast({
            title: '登录失败，请检查网络或初始化账号',
            icon: 'none'
        });
    } finally {
        loading.value = false;
    }
};

// 初始化管理员账号
const initAdminUser = async () => {
    if (loading.value) return;

    loading.value = true;

    try {
        const result = await uniCloud.callFunction({
            name: 'initAdminUser',
            data: {}
        });

        if (result.result.code === 0) {
            uni.showToast({
                title: 'Admin账号创建成功，默认密码：123456',
                icon: 'none',
                duration: 3000
            });
            showInitTip.value = false;
            loginForm.value.username = 'admin';
            loginForm.value.password = '';
        } else if (result.result.code === 1) {
            uni.showToast({
                title: result.result.message,
                icon: 'none'
            });
        } else {
            uni.showToast({
                title: result.result.message || '初始化失败',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('初始化失败', error);
        uni.showToast({
            title: '初始化失败，请检查网络',
            icon: 'none'
        });
    } finally {
        loading.value = false;
    }
};

// 页面加载时检查是否需要初始化提示
onMounted(() => {
    // 首次加载时显示初始化提示
    showInitTip.value = true;
});
</script>

<style>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f5f5f5;
}

.login-card {
    width: 400px;
    padding: 40px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-logo {
    text-align: center;
    margin-bottom: 20px;
}

.login-logo image {
    width: 100px;
    height: auto;
}

.login-title {
    text-align: center;
    margin-bottom: 30px;
}

.login-title text {
    font-size: 24px;
    font-weight: bold;
    color: #333;
}

.login-form {
    width: 100%;
}

.form-item {
    margin-bottom: 20px;
}

.form-label {
    font-size: 14px;
    color: #606266;
    margin-bottom: 10px;
}

.form-input {
    width: 100%;
    height: 40px;
    padding: 0 15px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    box-sizing: border-box;
    font-size: 14px;
}

.login-button {
    width: 100%;
    height: 40px;
    background-color: #409eff;
    border-radius: 4px;
    color: #fff;
    text-align: center;
    line-height: 40px;
    cursor: pointer;
    margin-top: 10px;
}

.login-button:active {
    background-color: #3a8ee6;
}

.login-button.disabled {
    background-color: #a0cfff;
    cursor: not-allowed;
}

.login-tip {
    margin-top: 20px;
    padding: 10px;
    background-color: #f0f9eb;
    color: #67c23a;
    border-radius: 4px;
    font-size: 12px;
    text-align: center;
    line-height: 1.4;
}

.init-button {
    margin-top: 10px;
    padding: 5px 0;
    background-color: #67c23a;
    color: #fff;
    border-radius: 4px;
    cursor: pointer;
}

.init-button:active {
    background-color: #5daf34;
}
</style>